package com.sxg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxg.convert.ConvertUtils;
import com.sxg.convert.SxgCommentConvert;
import com.sxg.dao.SxgCommentDao;
import com.sxg.entity.SxgCommentEntity;
import com.sxg.entity.SxgOrderEntity;
import com.sxg.entity.SxgUserEntity;
import com.sxg.query.SxgCommentChildQuery;
import com.sxg.query.SxgCommentQuery;
import com.sxg.service.SxgCommentService;
import com.sxg.service.SxgOrderService;
import com.sxg.service.SxgUserService;
import com.sxg.utils.SecurityUtils;
import com.sxg.utils.StringUtils;
import com.sxg.utils.code.AjaxResult;
import com.sxg.vo.SxgCommentVO;
import com.sxg.vo.req.CommentReqVo;
import com.sxg.vo.resp.CommentRespVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sxg.page.PageResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 评论表
 *
 * @author 浪漫写尽歌谱 3298751420@qq.com
 * @since 1.0.0 2024-03-07
 */
@Service
@AllArgsConstructor
public class SxgCommentServiceImpl extends ServiceImpl<SxgCommentDao, SxgCommentEntity> implements SxgCommentService {

    @Resource
    private SxgUserService sxgUserService;

    @Override
    public AjaxResult page(SxgCommentQuery query) {

        if (query.getGoodsId() == null) {
            return AjaxResult.error("商品id不能为空");
        }
        //查询顶层评论
        IPage<SxgCommentEntity> page = baseMapper.selectPage(PageResult.getPage(query), new QueryWrapper<SxgCommentEntity>().eq("top_comment_id", 0L).eq("is_delete", 0).eq("goods_id", query.getGoodsId()));
        //转换返回类型并查询子评论
        List<CommentRespVo> respVos = getCommentRespVos(page);
        return AjaxResult.success(respVos).put("total", page.getTotal());
    }

    @Override
    public AjaxResult childe(SxgCommentChildQuery query) {

        if (query.getCommentId() == null) {
            return AjaxResult.error("评论id不能为空");
        }

        IPage<SxgCommentEntity> page = baseMapper.selectPage(PageResult.getPage(query), new QueryWrapper<SxgCommentEntity>().eq("top_comment_id", query.getCommentId()).eq("is_delete", 0));
        //转换返回类型并查询子评论
        List<CommentRespVo> respVos = getCommentRespVos(page);
        return AjaxResult.success(respVos).put("total", page.getTotal());
    }

    private List<CommentRespVo> getCommentRespVos(IPage<SxgCommentEntity> page) {
        return page.getRecords().stream()
                .peek(
                        commentEntity -> {
                            Long replayUserId = commentEntity.getReplayUserId();
                            if (replayUserId != null) {
                                SxgUserEntity sxgUser = sxgUserService.selectUserByUserId(replayUserId);
                                commentEntity.setParentNickname(sxgUser.getNickName());
                                commentEntity.setParentAvatar(sxgUser.getAvatar());
                            }

                            Long userId = commentEntity.getUserId();
                            SxgUserEntity sxgUser = sxgUserService.selectUserByUserId(userId);
                            commentEntity.setUserNickname(sxgUser.getNickName());
                            commentEntity.setUserAvatar(sxgUser.getAvatar());
                        }
                ).map(ConvertUtils::toCommentRespVo)
                .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                .collect(Collectors.toList());
    }


    @Override
    public void save(SxgCommentVO vo) {
        SxgCommentEntity entity = SxgCommentConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(SxgCommentVO vo) {
        SxgCommentEntity entity = SxgCommentConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public AjaxResult save(CommentReqVo vo) {

        //判断图片格式是否正确
        if (StringUtils.isNotNull(vo.getImages())) {
            String[] split = vo.getImages().split(",");
            if (split.length == 0) {
                return AjaxResult.error("图片格式不正确");
            }
            for (String url : split) {
                if (StringUtils.isEmpty(url)) {
                    return AjaxResult.error("图片格式不正确");
                }
                if (!isImageUrl(url)) {
                    return AjaxResult.error("图片格式不正确");
                }
            }
        }

        // 判断是否是回复且回复评论或用户是否存在
        SxgUserEntity replayUserInfo = null;
        if (!StringUtils.isNull(vo.getTopCommentId()) && !StringUtils.isNull(vo.getParentId())) {
            SxgCommentEntity comment = getOne(new QueryWrapper<SxgCommentEntity>().select("id").eq("id", vo.getTopCommentId()));
            if (StringUtils.isNull(comment)) {
                return AjaxResult.error("回复评论不存在");
            }

        }

        if (StringUtils.isNotNull(vo.getReplyUserId())) {
            replayUserInfo = sxgUserService.selectUserByUserId(vo.getReplyUserId());
            if (replayUserInfo == null) {
                return AjaxResult.error("回复用户不存在");
            }
        }

        SxgUserEntity sxgUserEntity = sxgUserService.selectUserByUserId(SecurityUtils.getUserId());
        SxgCommentEntity sxgCommentEntity = new SxgCommentEntity();
        sxgCommentEntity.setGoodsId(vo.getGoodsId());
        sxgCommentEntity.setUserId(sxgUserEntity.getId());
        sxgCommentEntity.setContent(vo.getContent());
        sxgCommentEntity.setUserNickname(sxgUserEntity.getNickName());
        sxgCommentEntity.setUserAvatar(sxgUserEntity.getAvatar());
        sxgCommentEntity.setImages(vo.getImages());

        // 判断是否是回复
        if (replayUserInfo != null) {
            sxgCommentEntity.setTopCommentId(vo.getTopCommentId());
            sxgCommentEntity.setParentId(vo.getParentId());
            sxgCommentEntity.setReplayUserId(vo.getReplyUserId());
//            sxgCommentEntity.setParentAvatar(replayUserInfo.getAvatar());
//            sxgCommentEntity.setParentNickname(replayUserInfo.getNickName());
        }

        save(sxgCommentEntity);
        return AjaxResult.success("评论成功");

    }

    private boolean isImageUrl(String url) {
        Pattern pattern = Pattern.compile("([a-zA-Z0-9\\s_\\.-])+(.jpg|.png|.gif|.jpeg|.xbm|.tif|pjp|.svgz|.ico|.tiff|.svg|.jfif|.webp|.bmp|pjpeg|.avif')");
        Matcher matcher = pattern.matcher(url);
        return matcher.find();
    }

}